import { CloseOutline } from "antd-mobile-icons";
import React, { useEffect, useState } from "react";
import "./index.scss";
import { List, SearchBar, Toast } from "antd-mobile";
import {
  useLocation,
  useNavigate,
  useParams,
} from "react-router-dom";
import { brandList, modelYearList } from "@/api/modules/case";
import useStore from "@/store";
import { t } from "@/lang";
const StudySearch: React.FC = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [list, setList] = useState<any>([]);
  const [searchlist, setSearchList] = useState<any>([]);
  const { caseStudyForm, setCaseStudyForm } = useStore();

  useEffect(() => {
    if (params.type === "1") {
      brandList().then((res) => {
        setList(res.result);
        setSearchList(res.result);
      });
    } else if (params.type === "2") {
      modelYearList("1", caseStudyForm.swId as string).then((res: any) => {
        if (res.msg != "SUCCESS") {
          Toast.show({ icon: "fail", content: res.msg });
        } else {
          setList(res.data);
          setSearchList(res.data);
        }
      });
    } else if (params.type === "3") {
      modelYearList(
        "2",
        caseStudyForm.swId as string,
        caseStudyForm.model as string
      ).then((res:any) => {
        if (res.msg != "SUCCESS") {
          Toast.show({ icon: "fail", content: res.msg });
        } else {
          setList(res.data);
          setSearchList(res.data);
        }
      });
    }
  }, []);
  const navigateParams = (param: any) => {
    console.log("ccccccccccccc", param);

    const { brand, model, year, swId, ...asets } = caseStudyForm;
    if (params.type === "1") {
      setCaseStudyForm({ brand: param.nameEn, swId: param.swId, ...asets });
    } else if (params.type === "2") {
      setCaseStudyForm({ brand, swId, model: param, ...asets });
    } else if (params.type === "3") {
      setCaseStudyForm({
        brand,
        swId,
        model,
        year: param,
        ...asets,
      });
    }
  };
  const handleChange = (val: string) => {
    setSearchList(list.filter((item: any) => (item.nameEn || item).includes(val)));
    console.log(val);
  };
  return (
    <div id="case_search">
      <header>
        {t("case.t_2")}
        <CloseOutline
          onClick={() => navigate("/case/study", { replace: true })}
        />
      </header>
      <div className="search_wrap">
        <SearchBar
          placeholder={t("case.t_33")}
          onChange={(val: string) => handleChange(val)}
        />
      </div>

      <List>
        {searchlist.map((item: any) => (
          <List.Item
            key={params.type === "1" ? item.id : item}
            onClick={() => {
              navigateParams(item);
              navigate("/case/study", {
                replace: true,
              });
            }}
          >
            {item.nameEn || item}
          </List.Item>
        ))}
      </List>
    </div>
  );
};

export default StudySearch;
